package com.example.springboot.config.anotation.autoware;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author:ChenZhangKun
 * @Date: 2023/6/18 16:01
 */
@Component
public class MyIServiceProxyBean implements SuperAutowiredProxy, InvocationHandler {
    @Override
    public Object getBean(SuperAutowired superAutowired, ApplicationContext atx, Class<?> clazz) {
        String extData = superAutowired.extData();

        //
        if ("db".equals(extData)){
            // 比如： 从db加载要注入的bean
            String beanName = "";
            return atx.getBean(beanName);
        }else {
            // 动态代理生成该Bean
            if (clazz.isInterface()){
                return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{clazz}, this);
            }
        }

        return null;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 过滤掉Object类的方法
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(this, args);
        }

        System.out.println("MyIServiceProxyBean pre invoke: " + method.getName());
        return null;
    }
}
